package com.runa.monitor.platinterface.netservice.handler;

import com.runa.monitor.platinterface.base.BaseContainer;
import com.runa.monitor.platinterface.netservice.equipment.DtuPlcService;
import com.runa.monitor.platinterface.netservice.equipment.NetEqu;
import com.runa.monitor.platinterface.platService.NetEquService;
import com.runa.persistence.util.SpringContextUtil;
import com.runa.protocol.dto.DtuReport;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author zhuj
 */
@ChannelHandler.Sharable
public class DtuRegisterHandler extends SimpleChannelInboundHandler<DtuReport> {

    private static final Logger logger = LoggerFactory.getLogger(DtuRegisterHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DtuReport register) {
        Channel channel = ctx.channel();
        NetEquService netEquService = SpringContextUtil.getBean(NetEquService.class);
        NetEqu<String> netEqu = netEquService.getNetEquBySerial(register.getData());
        if (netEqu != null) {
            Set<DtuPlcService> serviceSet = BaseContainer.getDtu(register.getData());
            if (register.isMustAck()) {
                channel.writeAndFlush(register.getAck());
            }
            for (DtuPlcService service : serviceSet) {
                if (service.session() != null) {
                    if (service.session() == BaseContainer.getSession(channel.id().asLongText())) {
                        logger.info("客户端——{} 发送心跳 ", register.getData());
                    } else {
                        service.session().linked(ctx.channel());
                        BaseContainer.netStatusCallback().rccStatusChange(register.getData(), true);
                        logger.info("客户端——{} 已注册 ", register.getData());
                    }
                    break;
                }
            }
        } else {
            logger.info("非法客户端——{} ", register.getData());
            ctx.channel().close().addListener(future -> {
                if (future.isSuccess()) {
                    logger.info("关闭非法客户端连接：{} 成功", register.getData());
                } else {
                    logger.info("关闭非法客户端连接：{} 失败", register.getData());
                }
            });
        }
    }

}
